﻿using System;
using System.Text;
using System.Threading;
using MqttBased;
using System.Threading.Tasks;
using BusinessSample;
using Newtonsoft.Json;

namespace SubscribeClient
{
    class Program
    {
        private static MqttClientProvider _provider;
        static async Task Main(string[] args)
        {
            Console.WriteLine("这是一个订阅客户端案例，按任意键启动客户端");
            Console.ReadKey();
            _provider = new MqttClientProvider();
            var setting = new MqttSettingConfig().CreateDefaultSetting();
            await _provider.CreateClientInstance(setting);
            await _provider.SubscribeTopic("HardwareCall", HanderMessage);
            Console.WriteLine("按q键退出客户端");
            while (true)
            {
                var str = Console.ReadLine();
                if (str == "q")
                {
                    await _provider.CloseClient();
                    break;
                }
            }
        }


        public static async Task<MqttMessage> HanderMessage(byte[] input, Guid taskId)
        {
            var messageBody = JsonConvert.DeserializeObject<BusinessMessage>(Encoding.UTF8.GetString(input));
            var result = "";
            if (messageBody != null)
            {
                switch (messageBody.HandlerType)
                {
                    case HandlerType.OpenGate:
                        //处理开闸逻辑
                        result = "开闸成功!";
                        break;
                }
            }
            return new MqttMessage
            {
                MessageType = MessageType.Back,
                NeedReceived = false,
                MessageBody = new CarInfo
                {
                    Result = result
                },
                TaskId = taskId,
            };
        }
    }
}
